let userinfo = JSON.parse(localStorage.getItem('userinfo'));
document.querySelector('.username').innerHTML = userinfo;


//渲染列表
function render(data, page) {
    var str = ''

    str = data.map((item, index) => {
        return `<tr>
        <td>▢</td>
        <td>1</td>
        <td>ceo</td>
        <td>${item.name}</td>
        <td>${item.id}</td>
        <td>正常</td>
        <td>${new Date()}</td>
        <td class="dle">删除</td>
    </tr>`
    }).join('')

    if (str == '') {
        str = '<div style="text-align:center;color:red">未查询到数据!</div>'
    }
    document.querySelector('table tbody').innerHTML = str;
    console.log(data.length);
    document.querySelector('.change .num').innerHTML = data.length;
    if (page) {
        document.querySelector('.change .page').innerHTML = page;
    }else{
        
        document.querySelector('.change .page').innerHTML = 1;
    }

}

let addlist = document.querySelector('.content .add');
addlist.onclick = () => {

    add.style.display = 'block';
}


//新增
let ipts = document.querySelectorAll('.block input');
let btn = document.querySelector('.btn .btn1');
let add = document.querySelector('.add-box');
btn.onclick = () => {
    if (
        ipts[0].value &&
        ipts[1].value
    ) {
        axios.post('/add', {
            name: ipts[0].value,
            id: ipts[1].value
        }).then((res) => {
            console.log(res.data);
            alert(res.data.msg);
            add.style.display = 'none';
        })
    } else {
        alert('请填写所有信息！');
    }
}

//渲染请求
axios.get('/list', { params: { page: 1, count: 5 } }).then((res) => {
    render(res.data.list);
})
//点击下一页
var num = 1;
document.querySelector('.change .next').onclick = () => {
    num++;
    if (num >= 2) {
        num = 2;
    }
    axios.get('/list', { params: { page: num, count: 5 } }).then((res) => {
        render(res.data.list, 2);
    })
}
//点击上一页
document.querySelector('.change .prev').onclick = () => {
    num--;
    if (num <= 1) {
        num = 1;
    }
    axios.get('/list', { params: { page: num, count: 5 } }).then((res) => {
        render(res.data.list, num);
    })
}

//搜索
var findBtn = document.querySelector('.find .btn1');
var iptEle = document.querySelector('.find input');
findBtn.onclick = () => {
    axios.get('/search', { params: { searchkey: iptEle.value } }).then((res) => {
        render(res.data.list)
    })
}

//删除
document.querySelector('tbody').onclick = (e) => {
    if (e.target.classList.contains('dle')) {
        e.target.parentNode.remove();
    }
}